package com.sgb.trip.view.activity;

import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;

import com.sgb.link.R;
import com.sgb.link.databinding.ActivityCitySelectionBinding;
import com.sgb.link.entity.trip.AirportCityEntity;
import com.sgb.trip.viewmodel.CitySelectionViewModel;
import com.swgk.core.base.AppActivity;
import com.swgk.core.base.model.entity.RouterKey;
import com.swgk.core.dialog.DialogHelper;

/**
 * Describe:    选择地址
 * Author:  黄淋
 * Date:    2021/9/9
 */
public class CitySelectionActivity extends AppActivity {
    private ActivityCitySelectionBinding mBinding;
    private CitySelectionViewModel viewModel;

    @Override
    protected void initView() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_city_selection);
        viewModel = new ViewModelProvider(this).get(CitySelectionViewModel.class);
    }

    @Override
    protected void init() {
        mBinding.ivBack.setOnClickListener(view -> finish());
        initEvents();
        DialogHelper.showProgressDialog(this, "加载中").setCanceledOnTouchOutside(true);
        viewModel.getCitySelectionList();
        viewModel.ldData.observe(this, list -> mBinding.citySelectView.initAddressData(list));
        viewModel.ldDataHot.observe(this, list -> mBinding.citySelectView.initHot(list));
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void initEvents() {

        mBinding.citySelectView.setCheckedClickListener(name -> checkedCityResult(name));
        mBinding.cetCity.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String keyWords = s.toString();
                viewModel.queryCity(keyWords);
                viewModel.ldDataQuery.observe(CitySelectionActivity.this, list -> mBinding.citySelectView.filterData(keyWords, list));
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    /**
     * 选中城市
     *
     * @param entity
     */
    private void checkedCityResult(AirportCityEntity entity) {
        if (!TextUtils.isEmpty(entity.getCityName())) {
            Intent intent = new Intent();
            intent.putExtra(RouterKey.DATA, entity);
            setResult(200, intent);
            finish();
        }
    }

}
